package com.ywxx.dyhelper.utils;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Environment;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.DisplayMetrics;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.ywxx.dyhelper.BuildConfig;
import com.ywxx.dyhelper.R;
import com.ywxx.dyhelper.model.DYConfig;
import com.ywxx.dyhelper.model.TaskConfig;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.core.app.ActivityCompat;
import okhttp3.OkHttpClient;

public class ConstValues
{

    public static final String URL = "http://babysy.cn/index.php/systemlogined/api/";
    /**
     * 应用程序根目录
     */
    public static String RootPath = Environment.getExternalStorageDirectory() + "/hy_auto_cache";
    /**
     * 数据库路径
     */
    public static String DBFilePath = "";
    private static ConstValues _Instance = new ConstValues();

    public synchronized static ConstValues getInstance()
    {
        return _Instance;
    }

    /**************
     * 屏幕参数
     ********/
    public static float Density = 1;
    public static int Screen_Width;
    public static int Screen_Height;

    /***
     * 字体大小设置
     */
    public static float S_TextSize = 10;
    public static float M_TextSze = 12;
    public static float L_TextSze = 15;
    public static float Default_TextSze = 12;

    /**
     *
     */
    public static final String StartTaskAction = BuildConfig.APPLICATION_ID + ".start";

    /**
     * 任务配置
     */
    private ArrayList<DYConfig> dyconfigs = new ArrayList<>();

    public ArrayList<DYConfig> getDyConfigs()
    {
        return dyconfigs;
    }

    public void setDyConfigs(ArrayList<DYConfig> taskconfigs)
    {
        this.dyconfigs = taskconfigs;
    }

    public void InitParams(Context context)
    {
        //获取屏幕宽高
        {
            Display display = ((Activity) context).getWindowManager().getDefaultDisplay();
            DisplayMetrics displayMetrics = new DisplayMetrics();
            display.getMetrics(displayMetrics);

            Density = displayMetrics.density;
            Screen_Width = displayMetrics.widthPixels;
            Screen_Height = displayMetrics.heightPixels;
        }
        //获取参数的字体的参数
        {
            View view = LayoutInflater.from(context).inflate(R.layout.layout_base_textsize, null);
            TextView lab = (TextView) view.findViewById(R.id.s_textsize);
            S_TextSize = lab.getTextSize() / Density;

            lab = (TextView) view.findViewById(R.id.m_textsize);
            M_TextSze = lab.getTextSize() / Density;

            lab = (TextView) view.findViewById(R.id.l_textsize);
            L_TextSze = lab.getTextSize() / Density;

            lab = (TextView) view.findViewById(R.id.default_textsize);
            Default_TextSze = lab.getTextSize() / Density;
        }
    }

    public void InittPath(Context context)
    {
        //创建系统根目录
        File root = new File(RootPath);
        if (root.exists() == false && root.isDirectory() == false)
        {
            boolean isCreate = false;
            try
            {
                isCreate = root.mkdirs();
            } catch (Exception e)
            {
                Toast.makeText(context, e.getMessage(), Toast.LENGTH_LONG).show();
            }
            //如果没有SD卡则直接将目录放在应用程序里面
            if (isCreate == false)
            {
                RootPath = context.getFilesDir().getAbsolutePath();
            }
        }

        //数据库名称 缓存数据库
        DBFilePath = RootPath + "/auto_cache.db";
    }


    /**
     * http请求的连接
     */
    private OkHttpClient mClient = null;


    /**
     * 配置文件名称
     */
    private static final String ConfigName = "DYHelperConfig";

    /**
     * 通过配置文件保存参数
     * @param context 上下文
     * @param names 参数名称
     * @param values 泛型集合
     */
    public static void SaveValue(Context context, ArrayList<String> names, ArrayList<Object> values)
    {
        if (context == null || values == null)
            return;

        SharedPreferences preferences = context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        for (int n = 0; n < names.size(); n++)
        {
            Object value = values.get(n);
            String name = names.get(n);
            if (value == null)
                continue;
            if (value instanceof String)
            {
                editor.putString(name, value.toString());
            } else if (value instanceof Boolean)
            {
                editor.putBoolean(name, (Boolean) value);
            } else if (value instanceof Integer)
            {
                editor.putInt(name, (Integer) value);
            } else if (value instanceof Float)
            {
                editor.putFloat(name, (Float) value);
            } else if (value instanceof Long)
            {
                editor.putLong(name, (Long) value);
            }
        }

        // 提交保存
        editor.commit();
    }

    public static void SaveValue(Context context, String[] names, Object[] values)
    {
        if (context == null || values == null)
            return;

        SharedPreferences preferences = context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();

        for (int n = 0; n < names.length; n++)
        {
            Object value = values[n];
            String name = names[n];
            if (value == null)
                continue;
            if (value instanceof String)
            {
                editor.putString(name, value.toString());
            } else if (value instanceof Boolean)
            {
                editor.putBoolean(name, (Boolean) value);
            } else if (value instanceof Integer)
            {
                editor.putInt(name, (Integer) value);
            } else if (value instanceof Float)
            {
                editor.putFloat(name, (Float) value);
            } else if (value instanceof Long)
            {
                editor.putLong(name, (Long) value);
            }
        }

        // 提交保存
        editor.commit();
    }

    public static void SaveValue(Context context, String name, Object value)
    {
        if (context == null || value == null)
            return;

        SharedPreferences preferences = context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE);
        SharedPreferences.Editor editor = preferences.edit();
        if (value instanceof String)
        {
            editor.putString(name, value.toString());
        } else if (value instanceof Boolean)
        {
            editor.putBoolean(name, (Boolean) value);
        } else if (value instanceof Integer)
        {
            editor.putInt(name, (Integer) value);
        } else if (value instanceof Float)
        {
            editor.putFloat(name, (Float) value);
        } else if (value instanceof Long)
        {
            editor.putLong(name, (Long) value);
        }
        // 提交保存
        editor.commit();
    }

    public static String getValue(Context context, String name)
    {
        return getValue(context, name, "");
    }

    public static String getValue(Context context, String name, String defaultvalue)
    {
        if (context == null)
            return defaultvalue;
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).getString(name, defaultvalue);
    }

    public static int getIntValue(Context context, String name, int defaultvalue)
    {
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).getInt(name, defaultvalue);
    }

    public static boolean getBooleanValue(Context context, String name, boolean defaultvalue)
    {
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).getBoolean(name, defaultvalue);
    }

    public static long getLongValue(Context context, String name, long defaultvalue)
    {
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).getLong(name, defaultvalue);
    }

    public static float getLongValue(Context context, String name, float defaultvalue)
    {
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).getFloat(name, defaultvalue);
    }


    /**
     * 检验某个字段是否存在
     * @param context
     * @param key
     * @return
     */
    public static boolean containsKey(Context context, String key)
    {
        return context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).contains(key);
    }

    /**
     * 移除key
     * @param context
     * @param keys
     */
    public static void RemoveKey(Context context, String[] keys)
    {
        SharedPreferences.Editor editor = context.getSharedPreferences(ConfigName, Activity.MODE_PRIVATE).edit();
        for (String key : keys)
        {
            editor.remove(key);
        }
        editor.commit();
    }

    public OkHttpClient getClient()
    {
        if (mClient == null)
        {
            mClient = new OkHttpClient.Builder().connectTimeout(60, TimeUnit.SECONDS).readTimeout(90, TimeUnit.SECONDS).build();
        }
        return mClient;
    }

    /**
     * 获取设备唯一标识
     * @param context
     * @return
     */
    public static String getIMEI(Context context)
    {
        String DeviceId = "";
        try
        {
            TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
            {
                return "";
            }
            DeviceId = telephonyManager.getDeviceId();
        } catch (Exception e)
        {
        }
        if (DeviceId == null)
        {
            try
            {
                DeviceId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
            } catch (Exception e1)
            {
            }
        }

        return DeviceId == null ? "" : DeviceId.toUpperCase();
    }

    public static boolean CheckAppInstalled(Context context, String pkgName)
    {
        if (pkgName == null || pkgName.isEmpty())
        {
            return false;
        }
        final PackageManager packageManager = context.getPackageManager();
        List<PackageInfo> info = packageManager.getInstalledPackages(0);
        if (info == null || info.isEmpty())
            return false;
        for (int i = 0; i < info.size(); i++)
        {
            if (pkgName.equals(info.get(i).packageName))
            {
                return true;
            }
        }
        return false;
    }

    /*
     * @Author Sun Ruichuan
     * */
    public static PackageInfo getDyAPPInfo(Context context)
    {
        String packagename = "com.ss.android.ugc.aweme";
        PackageManager pckMan = context.getPackageManager();
        List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);
        for (PackageInfo pInfo : packageInfo)
        {
            if (pInfo.packageName.equals(packagename))
                return pInfo;
        }
        return null;
    }

    public static String getDyAPPVer(Context context)
    {
        String packagename = "com.ss.android.ugc.aweme";
        PackageManager pckMan = context.getPackageManager();
        List<PackageInfo> packageInfo = pckMan.getInstalledPackages(0);
        for (PackageInfo pInfo : packageInfo)
        {
            if (pInfo.packageName.equals(packagename))
                return pInfo.versionName;
        }
        return "未知";
    }

    public static String getdypackagenameid(String id)
    {
        return "com.ss.android.ugc.aweme:id/" + id;
    }

}
